export default class GLRandom {
    max = 100;
    MATH_RANGE = 100;  // 分成100份
    private _percentage: Map<number, number> = new Map();
    private _area: Map<number, number[]> = new Map();
    /**
     * 构造函数
     * @param {number} min  最小整数值
     * @param {number} max  最大整数值
     */
    constructor(max) {
        this.max = Math.trunc(max);
    }

    get percentage() {
        if (!this._percentage) {
            this._percentage = new Map();
        }
        return this._percentage;
    }

    /**
     * 分配比例
     * @param {Map} map 设置 值-百分比
     */
    set percentage(map) {
        let result = Array.from(map.values()).reduce((p, v) => {
            return p + v;
        }, 0);
        for (let i = 0; i < this.max; i++) {
            if (map.has(i)) {
                this._percentage.set(i, map.get(i));
            } else {
                this._percentage.set(i, 1);
            }
        }
        if (result < this.MATH_RANGE) {
            this._percentage.set(this.max, this.MATH_RANGE - result);
        }
        this.range();
    }
    private range() {
        let [start, keys] = [0, Array.from(this.percentage.keys())];
        for (let i = 0; i < keys.length; i++) {
            let temp = this.percentage.get(keys[i]);
            this._area.set(keys[i], [start, start += temp]);
        }
    }

    /**
     * 生成随机数
     */
    create(): number {
        let num = Math.random() * this.MATH_RANGE;
        let area = 0;
        this._area.forEach((item, index) => {
            if (num >= item[0] && num < item[1]) {
                area = index;
            }
        });
        return area;
    }
}
